package www.lagou.app;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import www.lagou.entity.Account;
import www.lagou.utils.DruidUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;

public class AccountTransfer {

    private String senderCard ;
    private String receiverCard ;
    private int amount;  //转账的金额钱数(元)
    private QueryRunner qr = null;
    private Account sender = null;

    public AccountTransfer() {

    }

    public AccountTransfer(String senderCard, String receiverCard, int amount) throws SQLException {
        this.senderCard = senderCard;
        this.receiverCard = receiverCard;
        this.amount = amount;
        qr = new QueryRunner(DruidUtils.getDataSource());
        String sql = "select * from account where card = ?";
        sender = qr.query(sql, new BeanHandler<Account>(Account.class), senderCard);
        if( null == sender) {
            System.out.println("转账人账户不存在哦！");
        }
        System.out.println("转账人信息：" + sender);
    }

    private boolean checkAccount() {
        //b) 判断转出方是否有足够余额，如果不足，提示信息：”余额不足！”，并结束程序；
        if (sender.getBalance() < amount) {
            System.out.println("余额不足！（当前余额）" + sender.getBalance() + ", 转账金额: " + amount);
            return false;
        }

        return true;
    }

    public void doTransfer() {

        try {
            //a) 使用连接池创建 QueryRunner 对象；
            // 建 核心类 自动模式 需要传递 数据库连接池对象
            qr = new QueryRunner(DruidUtils.getDataSource());
            if (checkAccount() == false) {
                System.out.println("余额不足，转账失败！");
                return;
            }

            //c) 通过卡号 进行转账的操作；
            //2.编写SQl
            String sql1 = "update account set balance = balance - ? where card = ?";
            String sql2 = "update account set balance = balance + ? where card = ?";
            //update account set balance = balance-5000 where card = '1122334455';
            //update account set balance = balance+5000 where card = '55443332211';

            //3.设置占位符的参数
            Object[] param1 = {amount, senderCard};
            Object[] param2 = {amount, receiverCard};

            //4.执行修改操作 自动模式不需要传入connection对象
            Date date = new Date();
            qr.update(sql1,param1);
            qr.update(sql2,param2);


            //模拟 转账之后出现异常
            //System.out.println(1 / 0);

            //d) 转账结束后, 将转入、转出记录分别写入到Transaction表中。
            insertTransaction(date);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {

        }

    }


    public void insertTransaction(Date date) throws SQLException {
        Connection con = null;

        //2.编写 占位符方式 SQL
        String sql = "insert into TRANSACTION values(?,?,?,?,?)";
        System.out.println("转账时间：" + date);
        //3.设置占位符的参数
        Object[] param0 = {null, sender.getCard(),
                "转出", amount, date};

        String senderGetSql = "select * from account where card = ?";
        Account receiver = qr.query(senderGetSql, new BeanHandler<Account>(Account.class), receiverCard);
        Object[] param1 = {null, receiver.getCard(),
                "转入", amount, date};

        //4.执行 update方法
        con = DruidUtils.getConnection();

        int i = qr.update(con, sql, param0);
        i = qr.update(con, sql, param1);
        //5.释放资源
        DbUtils.closeQuietly(con);
    }

    public void close() {
        // todo其他释放的操作
    }
}
